package com.costeaalex.MIDlets.remote.canvas;

import com.costeaalex.MIDlets.remote.communication.CommunicationManager;

public class Echoer extends Thread
	{
	
	private byte[] send=new byte[] {};
	private byte[] received=new byte[] {};
	private CommunicationManager cML;
	private boolean sending=false;
	private boolean isAlive;
	
	public Echoer(CommunicationManager cM)
		{
		cML=cM;
		isAlive=true;
		}
	
	public void run()
		{
		while(isAlive)
			{
			if(sending)
				{
				if(!checkEcho(send, received))
					{
					cML.send(send);
					try
						{
						sleep(10);
						}
					catch (InterruptedException e)
						{
						e.printStackTrace();
						}
					}
				else
					sending=false;
				}
			}
		}
	
	public void sendData(byte[] data)
		{
		send=data;
		sending=true;
		while(sending)
			{}
		}
	
	public void receiveData(byte[] data)
		{
		received=data;
		}
	
	public boolean isSending()
		{
		return sending;
		}
	
	private static boolean checkEcho(byte[] c1, byte[] c2)
		{
		int i;
		if(c1.length<c2.length && c1!=null && c2!=null)
			{
			for(i=0; i<c1.length; i++)
					if(c1[i]!=c2[i])
						return false;
			}
		else
			return false;
		return true;
		}
	
	}
